<template>
  <div v-loading="loading">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px" class="dataForm">
      <el-row>
        <el-col :span="24">
          <el-form-item :label="$t('基金名称')" prop="fundName">
            <template>
              <router-link
                target="_blank"
                :to="{path:'/fund/fundBasehome',query:{id:form.fundId}}"
                class="link_a"
              >{{ form.fundName }}
              </router-link>
            </template>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('拟设立规模') + $t('金额单位')" prop="scaleEstablished">
            <Money v-model="form.scaleEstablished" unit="w" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('拟注册地址')" prop="registeredAddress">
            <el-input v-model="form.registeredAddress" :placeholder="$t('拟注册地址')" show-word-limit maxlength="100" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('工商经营期限')" prop="businessPeriod">
            <el-input v-model="form.businessPeriod" :placeholder="$t('工商经营期限')" show-word-limit maxlength="100" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('委派代表')" prop="delegate">
            <el-input v-model="form.delegate" :placeholder="$t('委派代表')" show-word-limit maxlength="100" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('经营范围')" prop="businessScope">
            <el-input
              v-model="form.businessScope"
              type="textarea"
              :placeholder="$t('经营范围')"
              show-word-limit
              maxlength="1000"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <div style="margin-top: 15px">
        <!--股东/合伙人信息-->
        <div class="area-header">
          <span class="area-header-title">{{ $t('股东/合伙人信息') }}</span>
        </div>
        <el-table ref="table" :data="form.fundRegisteredInvestorList" border class="nowrapTable formTable">
          <el-table-column :label="$t('序号')" type="index" align="center" show-overflow-tooltip width="50">
            <template slot-scope="scope">
              {{ scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column :label="$t('出资人类型')" align="center" min-width="160">
            <template slot="header" slot-scope="{}">
              <i style="color: #ff4949;margin-right: 4px;">*</i>
              <span>{{ $t('出资人类型') }}</span>
            </template>
            <template slot-scope="scope">
              <el-form-item
                :prop="'fundRegisteredInvestorList.' + scope.$index + '.investorsType'"
                :rules="fundRegisteredInvestorListRules.investorsType"
              >
                <el-select
                  v-model="scope.row.investorsType"
                  :placeholder="$t('出资人类型')"
                  filterable
                  @change="empty(scope.row)"
                >
                  <el-option
                    v-for="dict in typeOptions"
                    :key="dict.dictValue"
                    :label="$t(dict.dictLabel)"
                    :value="dict.dictValue"
                  />
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>

          <el-table-column :label="$t('出资人名称')" align="center" min-width="160">
            <template slot="header" slot-scope="{}">
              <i style="color: #ff4949;margin-right: 4px;">*</i>
              <span>{{ $t('出资人名称') }}</span>
            </template>
            <template slot-scope="scope">
              <el-form-item
                :prop="'fundRegisteredInvestorList.' + scope.$index + '.investorsName'"
                :rules="fundRegisteredInvestorListRules.investorsName"
              >
                <el-select v-model="scope.row.investorsName" clearable filterable :placeholder="$t('出资人名称')">
                  <el-option
                    v-for="item in lpOptionsMap[scope.row.investorsType]"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>

          <el-table-column :label="$t('合伙人类型')" align="center" min-width="160">
            <template slot="header" slot-scope="{}">
              <i style="color: #ff4949;margin-right: 4px;">*</i>
              <span>{{ $t('合伙人类型') }}</span>
            </template>
            <template slot-scope="scope">
              <el-form-item
                :prop="'fundRegisteredInvestorList.' + scope.$index + '.partnerType'"
                :rules="fundRegisteredInvestorListRules.partnerType"
              >
                <el-select v-model="scope.row.partnerType" filterable clearable :placeholder="$t('合伙人类型')">
                  <el-option
                    v-for="dict in partnerTypeOptions"
                    :key="dict.dictValue"
                    :label="$t(dict.dictLabel)"
                    :value="dict.dictValue"
                  />
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>

          <el-table-column :label="$t('认缴时间')" align="center" min-width="150">
            <template slot="header" slot-scope="{}">
              <i style="color: #ff4949;margin-right: 4px;">*</i>
              <span>{{ $t('认缴时间') }}</span>
            </template>
            <template slot-scope="scope">
              <el-form-item
                :prop="'fundRegisteredInvestorList.' + scope.$index + '.subscriptionTime'"
                :rules="fundRegisteredInvestorListRules.subscriptionTime"
              >
                <DatePicker v-model="scope.row.subscriptionTime" :placeholder="$t('认缴时间')" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :label="$t('认缴金额') + $t('金额单位')" align="center" min-width="160">
            <template slot="header" slot-scope="{}">
              <i style="color: #ff4949;margin-right: 4px;">*</i>
              <span>{{ $t('认缴金额') }}{{ $t('金额单位') }}</span>
            </template>
            <template slot-scope="scope">
              <el-form-item
                :prop="'fundRegisteredInvestorList.' + scope.$index + '.subscriptionAmount'"
                :rules="fundRegisteredInvestorListRules.subscriptionAmount"
              >
                <Money v-model="scope.row.subscriptionAmount" unit="w" :placeholder="$t('认缴金额') +$t('金额单位')" />
              </el-form-item>
            </template>
          </el-table-column>

          <el-table-column v-if="!otherBtnHide" :label="$t('操作')" align="center" min-width="60px">
            <template slot-scope="scope">
              <el-button
                type="text"
                icon="el-icon-delete"
                @click="delFundRegisteredInvestorHandle(scope.$index, scope.row)"
              />
            </template>
          </el-table-column>
        </el-table>
        <div v-if="!otherBtnHide" class="tol">
          <el-button type="primary" icon="el-icon-plus" size="mini" @click="addFundRegisteredInvestorList">{{
            $t('添加')
          }}
          </el-button>
        </div>
      </div>
      <FileTable
        :list.sync="form.fileList"
        data-type="fund_registered"
        :business-id="autoBusinessId($route.query.id, form)"
        :btn-show="!otherBtnHide"
      />
    </el-form>
  </div>
</template>

<script>
import {
  saveFundRegistered,
  delFundRegisteredInvestor,
  getFundRegistered,
  getFundFullName
} from '@/api/fund/registered/fundRegistered'
import { changeNameByType } from '@/api/fund/investor/fundInvestor'
import { getCompanyByName } from '@/api/company/base/companyBase'
import { getFundName } from '@/api/fund/fundBase'

export default {
  data() {
    return {
      // 表单参数
      form: {
        fundRegisteredInvestorList: []
      },
      // 表单校验
      rules: {
        scaleEstablished: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        registeredAddress: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        businessPeriod: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        delegate: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        businessScope: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }]
      },
      // 股东/合伙人信息表单校验
      fundRegisteredInvestorListRules: {
        investorsType: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        investorsName: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        partnerType: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        subscriptionTime: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        subscriptionAmount: [{ required: true, message: this.$t('必填信息'), trigger: ['blur'] }]
      },
      // 遮罩层
      loading: false,
      // 操作按钮默认不展示
      buttonShow: true,
      otherBtnHide: false,
      // 出资人类型 字典
      typeOptions: [],
      investorsTypeOptions: [],
      lpOptionsMap: {},
      // 合伙人类型 字典
      partnerTypeOptions: [],
      // 天眼查查询条件
      tycParam: {
        id: '',
        companyName: '',
        tycId: ''
      }
    }
  },
  created() {
    // this.changeNameByTypeToSelect('GR')
    this.$bus.$emit('async_done')
    // 类型字典1
    // 合伙人类型
    this.getDicts('partner_type').then(response => {
      this.partnerTypeOptions = response.data
    })
  },
  methods: {
    // 初始化数据
    async init(data) {
      this.loading = true
      // 类型字典1
      const lpOptions = await this.getDicts('lp_type')
      lpOptions.data.forEach(item => {
        this.typeOptions.push(item)
      })
      // 类型字典2
      const mainOptions = await this.getDicts('main_body_type')
      mainOptions.data.forEach(item => {
        this.typeOptions.push(item)
      })
      for (let i = 0; i < this.typeOptions.length; i++) {
        this.changeNameByTypeToSelect(this.typeOptions[i].dictValue)
      }
      if (data != null && data.id !== undefined) {
        // 获取基金详细
        await getFundRegistered(data.id).then(response => {
          this.form = response.data
          this.loading = false
        }).catch(() => {
          this.loading = false
        })
      } else {
        this.reset()
        if (data != null) {
          this.form.fileList = data.fileList
        }
        await getFundFullName(this.$route.query.id).then(response => {
          this.form.fundName = response.data.fundName
          this.tycParam.companyName = response.data.fundFullName
          this.gainTyc()
          this.loading = false
        }).catch(() => {
          this.loading = false
        })
      }
    },
    // 获取天眼查数据
    async gainTyc() {
      if (this.form.fundName) {
        await getCompanyByName(this.tycParam).then(res => {
          if (res.msg !== 'nofind') {
            this.form.scaleEstablished = res.data.capitalRegistered ? res.data.capitalRegistered : 0
            this.form.registeredAddress = res.data.detailsRegistered
            var setDate = '无固定期限'
            var toTime = '无固定期限'
            if (res.data.setDate) {
              setDate = this.parseTime(res.data.setDate).toString()
            }
            if (res.data.toTime) {
              toTime = this.parseTime(res.data.toTime).toString()
            }
            this.form.businessPeriod = setDate + ' ' + '至' + ' ' + toTime
            this.form.delegate = res.data.legalPerson
            this.form.businessScope = res.data.businessScope
          }
        })
      }
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        fundId: this.$route.query.id,
        fundName: undefined,
        scaleEstablished: undefined,
        registeredAddress: undefined,
        businessPeriod: undefined,
        delegate: undefined,
        businessScope: undefined,
        actTitle: undefined,
        actId: undefined,
        actStatus: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined,
        delFlag: undefined
      }
      this.resetForm('form')
    },
    // 取消按钮
    cancel() {
      this.$parent.$parent.formOpen = false
      this.$parent.$parent.reset()
    },
    // 关闭form页面
    closeForm() {
      // 关闭form页面遮罩层
      this.loading = false
      // 关闭form页面
      if (this.$parent.$parent.formOpen !== undefined) {
        this.$parent.$parent.formOpen = false
      }
      // 刷新list页面
      if (this.$parent.$parent.getList !== undefined) {
        this.$parent.$parent.getList()
      }
    },

    /** 提交按钮 */
    submitForm: function(type) {
      return new Promise((resolve, reject) => {
        this.$refs['form'].validate(valid => {
          // 验证数据
          if (valid) {
            // 弹出遮罩层
            this.loading = true
            // 保存数据
            saveFundRegistered(this.form).then(response => {
              if (response.code === 200) {
                this.loading = false
                if (type === 'process') {
                  // 设置数据id方式启动流程后取消并再次启动会创建多条记录
                  this.form.id = response.data.id
                  // 启动流程
                  this.startProcess(response.data)
                  // 点击的仅保存
                } else {
                  this.msgSuccess(this.$t('保存成功'))
                  // 关闭form页面
                  this.closeForm()
                }
                resolve(response.data.id)
              } else {
                this.msgError(response.msg)
                this.loading = false
                reject(response)
              }
            }).catch(() => {
              this.loading = false
            })
          } else {
            this.locationError(document)
            reject()
          }
        })
      })
    },
    // 启动流程
    startProcess: async function(data) {
      var fundName = await getFundName(this.$route.query.id)
      this.loading = false
      // 启动流程时候传入的参数
      const processData = {}
      // 待办标题
      processData.title = '「' + fundName + '」 工商设立'
      // 业务表名
      processData.dataTable = 'fund_registered'
      // 业务ID
      processData.dataId = data.id
      // 业务表单地址(待办页面需要打开的页面)
      processData.formPath = '@/views/fund/registered/fundRegisteredForm'
      processData.viewPath = '@/views/fund/registered/fundRegisteredForm'
      // 菜单标识(根据菜单标识判断的走哪个流程)
      processData.menuKey = 'fund_registered'
      this.startProcessByMenu(processData, () => {
        this.form.actStatus = 'D'
        this.msgSuccess(this.$t('数据保存成功,流程启动成功'))
        this.closeForm()
      })
    },
    // 添加工商设立股东对象
    addFundRegisteredInvestorList() {
      const row = {
        id: undefined,
        registeredId: '',
        investorsType: '',
        investorsName: '',
        partnerType: '',
        subscriptionTime: '',
        subscriptionAmount: ''
      }
      if (!(this.form.fundRegisteredInvestorList instanceof Array)) {
        this.$set(this.form, 'fundRegisteredInvestorList', [])
      }
      this.$nextTick(() => {
        this.form.fundRegisteredInvestorList.push(row)
      })
    },
    // 删除工商设立股东对象
    delFundRegisteredInvestorHandle(index, row) {
      // eslint-disable-next-line no-undef
      const id = row.id
      if (id !== undefined && id !== '' && id != null) {
        this.$confirm(this.$t('是否确认删除?'), this.$t('警告'), {
          confirmButtonText: this.$t('确定'),
          cancelButtonText: this.$t('取消'),
          type: 'warning'
        })
          .then(function() {
            return delFundRegisteredInvestor(id)
          }).then(() => {
          this.form.fundRegisteredInvestorList.splice(index, 1)
          return this.msgSuccess(this.$t('删除成功'))
        })
          .catch(function() {
          })
      } else {
        this.form.fundRegisteredInvestorList.splice(index, 1)
      }
    },
    // 根据类型 改变名称下拉
    changeNameByTypeToSelect: function(type) {
      if (type !== null && type !== undefined && type !== '') {
        if (this.lpOptionsMap[type] === null || this.lpOptionsMap[type] === undefined) {
          changeNameByType(type).then(response => {
            this.lpOptionsMap[type] = response.data
            // this.loading = true
            // this.$forceUpdate()
            // this.loading = false
            console.log(this.lpOptionsMap)
          })
        }
      }
    },
    empty(row) {
      row.investorsName = undefined
    }
  }
}
</script>
